/**
 * @author zjkermit
 * @email zjkermit@gmail.com
 * @date Apr 14, 2014
 */
package zhoujian.oj.leetcode;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

/**
 * @version 1.0
 * @description Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

                For example,
                Given n = 3, your program should return all 5 unique BST's shown below.
                
                   1         3     3      2      1
                    \       /     /      / \      \
                     3     2     1      1   3      2
                    /     /       \                 \
                   2     1         2                 3
 */
public class UniqueBinarySearchTreesII {

	@SuppressWarnings("unused")
    private class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;
	
		TreeNode(int x) {
		    val = x;
		}
    }
    
    // do not understand!!!
	public List<TreeNode> generateTrees(int n) {
		return generateTrees(1, n);
	}

	private List<TreeNode> generateTrees(int start, int end) {
		List<TreeNode> res = new ArrayList<TreeNode>();
		if (start > end) {
			res.add(null);
			return res;
		}
		
		for (int i = start; i <= end; i++) {
			List<TreeNode> leftList = generateTrees(start, i - 1);
			List<TreeNode> rightList = generateTrees(i + 1, end);
			
			for (int j = 0; j < leftList.size(); j++) {
				for (int k = 0; k < rightList.size(); k++) {
					TreeNode root = new TreeNode(i);
					root.left = leftList.get(j);
					root.right = rightList.get(k);
					res.add(root);
				}
			}
		}
		
		return res;
	}
    
    @Test
    public void test() {
		List<TreeNode> res = generateTrees(3);
		System.out.println(res);
    }
}
